package com.dce.dev.api.common.tools.json;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

/**
 * 日期类型反序列化器
 * <p>
 * 将 long 类型值转换为 {@link Date} 类型值
 */
public class DateJsonDeserializer extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(final JsonParser jp, final DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        try {
            final long longValue = jp.getLongValue();
            final Date dateValue = new Date(longValue);
            return dateValue;
        } catch (final JsonParseException e) {
            try {
                final String date = jp.getText();
                final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                final Date dateValue = format.parse(date);
                return dateValue;
            } catch (final ParseException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
